package sis.security;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-07-31 11:59
 * @notify
 * @version 1.0
 */

import junit.framework.TestCase;
import sis.security.PermissionException;
import sis.security.SecureProxy;

import java.lang.reflect.Method;

public class SecureProxyTest extends TestCase {
    public static final String secureMethodName = "secure";
    public static final String insecureMethodName = "insecure";
    public Object object;
    //代理类
    public SecureProxy proxy;
    public boolean secureMethodCalled;
    public boolean insecureMethodCalled;

    public void setUp() {
        //创建一个代理对象前身
        object = new Object() {
            public void secure() {
                secureMethodCalled = true;
            }

            public void insecure() {
                insecureMethodCalled = true;
            }
        };
        //创建一个代理对象 给出 代理对象前身 和需要代理的方法
        proxy = new SecureProxy(object, secureMethodName);
    }

    public void testSecureMethod() throws Throwable {
        // 拿到 代理对象前身 的具体方法. 也就是在创建 代理对象时 指定的那个需要增强的方法 method
        Method secureMethod = object.getClass().getDeclaredMethod(
                secureMethodName, new Class[]{});
        try {
            proxy.invoke(proxy, secureMethod, new Object[]{});
            fail("expected PermissionException");
        } catch (PermissionException exception) {
            assertFalse(secureMethodCalled);
        }
    }

    public void testInsecureMethod() throws Throwable {
        Method insecureMethod = object.getClass().getDeclaredMethod(
                insecureMethodName, new Class[]{});

        proxy.invoke(proxy, insecureMethod, new Object[]{});
        assertTrue(insecureMethodCalled);
    }

}


